﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Implement;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.RefundCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.RefundHarder
{
    public class UpdateAccountbalanceHarder : IRequestHandler<UpdateAccountbalanceCommand, APIResult<object>>
    {

        private readonly IBaseRepository<Accountbalance> repository;
        private readonly IBaseRepository<Refund> Refundrepository;

        public UpdateAccountbalanceHarder(IBaseRepository<Accountbalance> repository, IBaseRepository<Refund> refundrepository)
        {
            this.repository = repository;
            Refundrepository = refundrepository;
        }

        public async Task<APIResult<object>> Handle(UpdateAccountbalanceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<object> result = new APIResult<object>();

                var model = repository.GetAll().Where(x=>x.PatientId == request.PatientId).First();
                model.Balance = request.Balance;


                var dto = repository.Update(model).Result;
                Refund refund = new Refund();

                refund.PatientId = request.PatientId;
                refund.RefundAmount = request.RefundAmount;
                refund.CardBalance = request.Balance;
                refund.IsDeleted = false;
                refund.RefundNo = "TK" + DateTime.Now.ToString("yyyyMMddHHmmss");
                refund.RefundTime = DateTime.Now;
                refund.RefundPath = "微信";
                refund.RefundStatus = "已退款";
                refund.Source = "微信小程序;";
                refund.BusinessType = "就诊卡退款";
                refund.CreateTime = DateTime.Now;
                await Refundrepository.AddAsync(refund);

                if (dto > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "修改成功";
                    result.Data = dto;
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "修改失败";
                    result.Data = dto;
                }
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
